package abc.datasource;

import abc.base.BaseController;
import abc.config.DatasourceConfigure;
import abc.utils.RequestUtil;
import abc.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.List;

@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE+1)
public class RequestMatchSchemaDSFilter implements WebFilter {

    @Autowired
    DatasourceConfigure datasourceConfigure;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        setDS(exchange);
        return chain.filter(exchange);
    }

    private void setDS(ServerWebExchange exchange) {
        List<String> params = StringUtil.splitString2List(exchange.getRequest().getPath().value(), "/");
        if(params.size()<3) {
            return;
        }
        datasourceConfigure.getDatasource().entrySet().forEach(a-> {
            if(params.get(2).equals(a.getKey())) {
                if(StringUtil.isNotEmpty(a.getValue().getName())) {
                    DynamicDataSourceContextHolder.setDataSourceType(a.getKey());
                    log.info("set datasource: " + a.getValue().getName());
                }
            }
        });
    }
}
